package com.visionblue.business.ship.base

import com.visionblue.business.ship.model.Results
import com.visionblue.business.ship.model.bean.response.CommonResponse
import com.visionblue.business.ship.model.bean.response.EmptyResponse
import com.visionblue.business.ship.model.exception.ResponseException
import kotlinx.coroutines.coroutineScope
import java.io.IOException

/**
 * @author: xlh
 * @date: 2020-04-10 2:24 PM
 * @desc:
 */
abstract class BaseRepository {

    suspend fun <T : Any> safeApiCall(
        call: suspend () -> CommonResponse<T>, errorMessage: String = "网络异常，请稍后重试"
    ): Results<T> {
        return try {
            executeResponse(call())
        } catch (e: Exception) {
            // An exception was thrown when calling the API so we're converting this to an IOException
            Results.Error(IOException(errorMessage, e))
        }
    }

    private suspend fun <T : Any> executeResponse(
        response: CommonResponse<T>
    ): Results<T> {
        return coroutineScope {
            if (response.isSuccess()) {
                Results.Success(response.data)
            } else {
                Results.Error(ResponseException(response))
            }
        }
    }
}